package com.lagou.util;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class RpcDecoding extends ByteToMessageDecoder {

    private Class<?> clazz;

    private Serializer serializer;

    // 消息头：发送端写的是一个int，占用4字节。
    private final static int HEAD_LENGTH = 4;

    public RpcDecoding(Class<?> clazz, Serializer serializer){
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.isReadable()){
            if (in.readableBytes() < HEAD_LENGTH)return;
            //标记当前读的下标位置
            in.markReaderIndex();
            int len = in.readInt();
            //如果读到的消息体小于消息长度，则重置到mark位置
            if (in.readableBytes() < len){
                in.resetReaderIndex();
                return;
            }
            byte[] bytes = new byte[len];
            in.readBytes(bytes);
            Object body = serializer.deserialize(clazz, bytes);
            out.add(body);
        }
    }
}
